
addEventListener( "message", function( event ){
	var imageData = event.data.imageData;
	var renderStyle = event.data.renderStyle;
	
	switch( renderStyle ){
		case 1: imageData = grayScale( imageData ); break;
		case 2: imageData = brightness( imageData ); break;
		case 3: imageData = threshold( imageData ); break;
	}
	postMessage( imageData );
}, false );


function grayScale( imageData ){
	var pix = imageData.data;
	var adjust;
	for (var i = 0, n = pix.length; i < n; i += 4) {
	    adjust = pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
	    pix[i  ] = adjust;   // red
	    pix[i+1] = adjust;   // green
	    pix[i+2] = adjust;   // blue
	 }
	
	return imageData;
}

function brightness( imageData ){
	var pix = imageData.data;
	for (var i = 0, n = pix.length; i < n; i += 4) {
	    pix[i  ] += 80;   // red
	    pix[i+1] += 80;   // green
	    pix[i+2] += 80;   // blue
	 }
	
	return imageData;
}

function threshold( imageData ) {
	var pix = imageData.data;
	var adjust;
	var div = 180;
	for (var i = 0, n = pix.length; i < n; i += 4) {
	    adjust = ( pix[i  ] * .2126 + pix[i+1] * .7152 + pix[i+2] * .0722 > div ) ? 255:0;
	    pix[i  ] = adjust;   // red
	    pix[i+1] = adjust;   // green
	    pix[i+2] = adjust;   // blue
	 }
	
	return imageData;
};

function contrast( imageData ) {
	var pix = imageData.data;
	var average;
	var contrastValue = 10;
	for (var i = 0, n = pix.length; i < n; i += 4) {
		average = Math.round( ( pix[i] + pix[i+1] + pix[i+2] ) / 3 );
		
		if (average > 127){
			pix[i] += ( pix[i]/average ) * contrastValue;
			pix[i+1] += ( pix[i+1]/average ) * contrastValue;
			pix[i+2] += ( pix[i+2]/average ) * contrastValue;
		 }else{
			 pix[i] -= ( pix[i]/average ) * contrastValue;
			 pix[i+1] -= ( pix[i+1]/average ) * contrastValue;
			 pix[i+2] -= ( pix[i+2]/average ) * contrastValue;
		 }
	 }
	
	return imageData;
};



